package com.example.mp.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.example.mp.entity.UserEntity;
import com.example.mp.service.UserService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @ApiOperation("主库")
    @RequestMapping(value = "/getMasterUserList", method = RequestMethod.POST)
    public List<UserEntity> getMasterUserList() {
        return userService.getMasterUserList();
    }

    @ApiOperation("新增数据")
    @RequestMapping(value = "/insertUser", method = RequestMethod.POST)
    public void insertUser() {
        TimeInterval timer = DateUtil.timer();
        List<UserEntity> list = new ArrayList();
        for (int i = 0; i < 1000000; i++) {
            UserEntity userEntity = new UserEntity();
            userEntity.setAge("20");
            userEntity.setName("张三");
            userEntity.setEmail("www." + i + "@qq.com");
            userEntity.setDescription("描述" + i);
            userEntity.setPasswd("密码" + i);
            log.info(new Gson().toJson(userEntity));
            list.add(userEntity);
        }
        List<List<UserEntity>> lists = ListUtil.split(list, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<UserEntity> listSub : lists) {
            userService.insertUser(listSub, countDownLatch);
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的;
            log.info("插入" + list.size() + "条数据,总用时:" + timer.interval());
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            log.error("阻塞异常:" + e.getMessage());
        }
    }

    @ApiOperation("导出数据")
    @RequestMapping(value = "/exportUser", method = RequestMethod.POST)
    public void exportUser() {
        userService.exportUser();
    }

    @ApiOperation("从库1接口")
    @RequestMapping(value = "/getSlaveOneUserList", method = RequestMethod.POST)
    public List<UserEntity> getSlaveOneUserList() {
        return userService.getSlaveOneUserList();
    }

    @ApiOperation("从库2接口")
    @RequestMapping(value = "/getSlaveTwoUserList", method = RequestMethod.POST)
    public List<UserEntity> getSlaveTwoUserList() {
        return userService.getSlaveTwoUserList();
    }


}